package com.ry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ry.dao.FollowerDao;
import com.ry.model.dto.FollowerDTO;
import com.ry.model.entity.Follower;
import com.ry.service.FollowerService;
import com.ry.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ry
 * @since 2021-11-11 21:07
 **/
@Service
public class FollowerServiceImpl implements FollowerService {
    @Autowired
    private FollowerDao followerDao;
    @Autowired
    private UserService userService;

    @Override
    public Integer add(FollowerDTO followerDTO) {
        Follower entity = new Follower();
        entity.setStateId(followerDTO.getStateId());
        entity.setUserId(followerDTO.getUserId());
        entity.setCreateTime(LocalDateTime.now().toString());

        followerDao.insert(entity);

        return entity.getId();
    }

    /**
     * 一个用户对于一个状态只能点赞一次
     *
     */
    @Override
    public void delete(FollowerDTO followerDTO) {
        QueryWrapper<Follower> wrapper = new QueryWrapper<>();
        Integer stateId = followerDTO.getStateId();
        Integer userId = followerDTO.getUserId();
        if (stateId == null || userId == null){
            throw new RuntimeException("删除点赞的非法操作");
        }

        wrapper.eq("user_id",userId);
        wrapper.eq("state_id", stateId);

        int delete = followerDao.delete(wrapper);
    }

    @Override
    public List<FollowerDTO> selectByStateId(Integer stateId) {
        QueryWrapper<Follower> wrapper = new QueryWrapper<>();
        wrapper.eq("state_id",stateId);
        List<Follower> followers = followerDao.selectList(wrapper);

        List<FollowerDTO> infos = followers.stream().map(entity -> {
            FollowerDTO followerDTO = new FollowerDTO();
            followerDTO.setId(entity.getId());
            followerDTO.setStateId(entity.getStateId());
            followerDTO.setUserId(entity.getUserId());
            followerDTO.setCreateTime(entity.getCreateTime());
            followerDTO.setUsername(userService.getUserById(entity.getUserId()).getNickname());

            return followerDTO;
        }).collect(Collectors.toList());

        return infos;
    }
}
